package utils.okhttp;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import module.Aria2;
import okhttp3.*;
import okio.ByteString;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import utils.json.InitConfig;

import java.io.IOException;

@Slf4j
public class OkHttpUtil {
    private final static OkHTTPConfig config = OkHTTPConfig.getInstance();
    private final static OkHttpClient client = config.getClient();
    private static final Request WSRequest = config.getWSRequest();
    private static WebSocket webSocket = null;
    private static final OkHttpUtil instance = new OkHttpUtil();

    private OkHttpUtil() {
        if (webSocket == null && InitConfig.isEnableAria2()) {
            StartAria2WevSocket();
        }
    }

    public WebSocket getWebSocket() {
        return webSocket;
    }

    public static OkHttpUtil getInstance() {
        return instance;
    }

    /**
     * 启动WebSocket连接。
     */
    private static void StartAria2WevSocket() {
        webSocket = client.newWebSocket(WSRequest, new Aria2WebSocketListener());
    }

    public int PushPlusPost(String url, String json) {
        RequestBody body = RequestBody.create(json, MediaType.parse("application/json;charset=UTF-8"));
        Request request = new Request.Builder().url(url).post(body).build();
        Call call = client.newCall(request);
        Response response = null;
        try {
            response = call.execute();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return response == null ? -1 : response.code();
    }

    /**
     * 重写WebSocketListener类。
     */
    private static class Aria2WebSocketListener extends okhttp3.WebSocketListener {
        public Aria2WebSocketListener() {
            super();
        }

        @Override
        public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
            log.info("WS关闭");
        }

        @Override
        public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
            log.info("WS关闭");
        }

        @Override
        public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
            log.info("Aria2 Server：连接失败。");
        }

        @Override
        public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
            JSONObject json = (JSONObject) JSONObject.parse(text);
            String id = json.getString("id");
            if (id != null) {
                Aria2.isPushSuccess(id);
            }
//            log.info("收到Aria2服务器消息：" + text);
        }

        @Override
        public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) {
        }

        @Override
        public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) {
            log.info("Aria2 Server：连接成功。");
        }
    }
}
